import * as d from 'debug';

/**
 * 生成 debug
 * @param namespace - debug 逻辑命名
 */
export const createDebug = (namespace: string) => {
  return d(`ts-lib-basic:${namespace}`);
};

const MAX_SAFE_INTEGER = 9007199254740991;

function isLength(value: any) {
  return (
    typeof value == 'number' &&
    value > -1 &&
    value % 1 == 0 &&
    value <= MAX_SAFE_INTEGER
  );
}

/**
 * 判断是否是 arrayLike，参考 lodash
 * @example isArrayLike([]) -> true
 * @param value 要判断的元素
 */
export const isArrayLike = (value: any) => {
  return value != null && typeof value != 'function' && isLength(value.length);
};

export const getVal = (obj: any, key: string) => {
  let keyList = key.split('.');
  let value = obj;
  for (let i = 0; i < keyList.length; i++) {
    if (
      Object.prototype.toString.call(value) === '[object Object]' ||
      Object.prototype.toString.call(value) === '[object Array]'
    ) {
      value = value[keyList[i]];
    } else {
      if (i === 0) {
        console.log('传入的不是对象或数组形式，将返回undefined');
        value = undefined;
      }
      break;
    }
  }
  return value;
};
